/**
 * 注册页面组件
 * 提供用户注册功能，包括：
 * - 基础信息注册（用户名、手机号、密码等）
 * - 身份信息验证（身份证号）
 * - 角色选择（学生/教师）
 * - 教师特有信息收集
 * - 响应式布局支持
 */

<template>
  <div class="register-container">
    <div class="register-box">
      <!-- 左侧装饰区域 -->
      <div class="register-left">
        <div class="brand">
          <div class="logo">EDU</div>
          <h1>教育共享平台</h1>
          <p class="slogan">让知识触手可及</p>
          <div class="features">
            <div class="feature-item">
              <div class="feature-icon">📚</div>
              <div class="feature-text">
                <h3>海量优质课程</h3>
                <p>汇聚各领域精品课程，满足多样化学习需求</p>
              </div>
            </div>
            <div class="feature-item">
              <div class="feature-icon">👨‍🏫</div>
              <div class="feature-text">
                <h3>专业教师团队</h3>
                <p>资深教师在线授课，保证教学质量</p>
              </div>
            </div>
            <div class="feature-item">
              <div class="feature-icon">🎯</div>
              <div class="feature-text">
                <h3>个性化学习</h3>
                <p>智能推荐学习内容，打造专属学习计划</p>
              </div>
            </div>
          </div>
          <img src="@/assets/Register.png" alt="教育平台注册图片" class="brand-image">
        </div>
      </div>

      <!-- 右侧表单区域 -->
      <div class="register-right">
        <div class="register-header">
          <h2>欢迎注册</h2>
        </div>
        <form class="register-form" @submit.prevent="handleSubmit">
          <!-- 用户名输入 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">👤</div>
              <input 
                type="text" 
                v-model="formData.userName" 
                placeholder="用户名"
                required
              >
            </div>
          </div>

          <!-- 手机号输入 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">📱</div>
              <input 
                type="tel" 
                v-model="formData.mobile" 
                placeholder="手机号"
                required
              >
            </div>
          </div>

          <!-- 验证码输入 -->
          <div class="form-group">
            <div class="input-group verification-group">
              <div class="input-icon">🔑</div>
              <input 
                type="text" 
                v-model="formData.verificationCode" 
                placeholder="验证码"
                required
              >
              <button 
                type="button" 
                class="send-code-btn" 
                :disabled="cooldown > 0 || !formData.mobile"
                @click="sendVerificationCode"
              >
                {{ cooldown > 0 ? `${cooldown}s` : '获取验证码' }}
              </button>
            </div>
          </div>

          <!-- 真实姓名输入 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">👨</div>
              <input 
                type="text" 
                v-model="formData.realName" 
                placeholder="真实姓名（必填）"
                required
              >
            </div>
          </div>

          <!-- 身份证号输入 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">🆔</div>
              <input 
                type="text" 
                v-model="formData.idCard" 
                placeholder="身份证号码（必填）"
                @blur="validateIdCard"
                required
              >
            </div>
            <span class="error-message" v-if="idCardError">{{ idCardError }}</span>
          </div>

          <!-- 密码输入 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">🔒</div>
              <input 
                :type="showPassword ? 'text' : 'password'" 
                v-model="formData.password" 
                placeholder="密码（必须包含字母和数字，不少于6位）"
                @focus="showPasswordTip = true"
                @blur="showPasswordTip = false"
                required
              >
              <div class="password-toggle" @click="showPassword = !showPassword">
                <div class="eye-icon">
                  <template v-if="showPassword">👁️</template>
                  <template v-else>👁️‍🗨️</template>
                </div>
              </div>
            </div>
            <div class="password-tip" v-show="showPasswordTip">
              <p>密码要求：</p>
              <ul>
                <li :class="{ valid: hasNumber }">✓ 包含数字</li>
                <li :class="{ valid: hasLetter }">✓ 包含字母</li>
                <li :class="{ valid: isLongEnough }">✓ 长度不少于6位</li>
              </ul>
            </div>
          </div>

          <!-- 确认密码输入 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">🔒</div>
              <input 
                :type="showConfirmPassword ? 'text' : 'password'" 
                v-model="formData.confirmPassword" 
                placeholder="确认密码"
                required
              >
              <div class="password-toggle" @click="showConfirmPassword = !showConfirmPassword">
                <div class="eye-icon">
                  <template v-if="showConfirmPassword">👁️</template>
                  <template v-else>👁️‍🗨️</template>
                </div>
              </div>
            </div>
          </div>

          <!-- 学历选择 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">🎓</div>
              <select v-model="formData.education" required>
                <option value="">请选择学历</option>
                <option value="小学">小学</option>
                <option value="初中">初中</option>
                <option value="高中">高中</option>
                <option value="专科">专科</option>
                <option value="本科">本科</option>
                <option value="硕士">硕士</option>
                <option value="博士">博士</option>
              </select>
            </div>
          </div>

          <!-- 角色选择 -->
          <div class="form-group">
            <div class="input-group role-input-group">
              <div class="input-icon">👥</div>
              <div class="role-mini-selector">
                <div 
                  class="role-mini-option" 
                  :class="{ active: formData.role === 'student' }" 
                  @click="selectRole('student')"
                >
                  <span class="role-mini-icon">👨‍🎓</span>
                  <span>学生</span>
                </div>
                <div class="role-divider"></div>
                <div 
                  class="role-mini-option" 
                  :class="{ active: formData.role === 'teacher' }" 
                  @click="selectRole('teacher')"
                >
                  <span class="role-mini-icon">👨‍🏫</span>
                  <span>教师</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 教师特有信息 -->
          <div v-if="formData.role === 'teacher'" class="teacher-fields">
            <h3 class="teacher-section-title">教师信息</h3>
            
            <!-- 教龄输入 -->
            <div class="form-group">
              <div class="input-group">
                <div class="input-icon">🕒</div>
                <input 
                  type="number" 
                  v-model="teacherData.teachingAge" 
                  placeholder="教龄（年）"
                  min="0"
                  max="50"
                >
              </div>
            </div>
            
            <!-- 教学风格输入 -->
            <div class="form-group">
              <div class="input-group">
                <div class="input-icon">🎓</div>
                <input 
                  type="text" 
                  v-model="teacherData.teachingStyle" 
                  placeholder="教学风格"
                >
              </div>
            </div>
            
            <!-- 教师资格证输入 -->
            <div class="form-group">
              <div class="input-group">
                <div class="input-icon">📜</div>
                <input 
                  type="text" 
                  v-model="teacherData.certification" 
                  placeholder="教师资格证"
                >
              </div>
            </div>
            
            <!-- 教师简介输入 -->
            <div class="form-group">
              <div class="input-group textarea-group">
                <div class="input-icon">📝</div>
                <textarea 
                  v-model="teacherData.introduction" 
                  placeholder="教师简介..."
                  rows="3"
                ></textarea>
              </div>
            </div>
          </div>

          <!-- 表单底部 -->
          <div class="form-footer">
            <button type="submit" :disabled="loading" class="submit-btn">
              {{ loading ? '注册中...' : '立即注册' }}
            </button>
            <div class="login-link">
              已有账号？ <router-link to="/login">立即登录</router-link>
            </div>
          </div>
        </form>
      </div>
    </div>
    <!-- 返回顶部组件 -->
    <BackToTop />
  </div>
</template>

<script>
/**
 * 注册页面组件
 * @description 用户注册表单，包含用户名、手机号、验证码、密码等字段
 */
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { register, sendSmsCode, checkSmsCode } from '@/api/user'
import { useRouter } from 'vue-router'
import BackToTop from '@/components/common/BackToTop.vue'

export default {
  name: 'RegisterView',
  components: {
    BackToTop
  },
  
  setup() {
    const router = useRouter()
    
    // 表单数据
    const formData = reactive({
      userName: '',           // 用户名
      mobile: '',            // 手机号
      verificationCode: '',  // 验证码
      password: '',          // 密码
      confirmPassword: '',   // 确认密码
      education: '',         // 学历
      role: 'student',       // 角色（默认为学生）
      realName: '',          // 真实姓名
      idCard: ''             // 身份证号
    })

    // 教师特有数据
    const teacherData = reactive({
      teachingAge: "",       // 教龄
      teachingStyle: "",     // 教学风格
      certification: "",     // 教师资格证
      introduction: ""       // 教师简介
    })

    // 状态变量
    const cooldown = ref(0)              // 验证码倒计时
    const loading = ref(false)           // 提交按钮加载状态
    const showPasswordTip = ref(false)   // 密码提示显示状态
    const mobileError = ref('')          // 手机号错误信息
    const isMobileValid = ref(false)     // 手机号验证状态
    const idCardError = ref('')          // 身份证号错误信息
    const showPassword = ref(false)      // 密码显示状态
    const showConfirmPassword = ref(false) // 确认密码显示状态

    /**
     * 验证手机号格式
     * 检查手机号是否为空和格式是否正确
     */
    const validateMobile = () => {
      const mobileRegex = /^1[3-9]\d{9}$/
      if (!formData.mobile) {
        mobileError.value = '请输入手机号'
        isMobileValid.value = false
      } else if (!mobileRegex.test(formData.mobile)) {
        mobileError.value = '请输入正确的手机号'
        isMobileValid.value = false
      } else {
        mobileError.value = ''
        isMobileValid.value = true
      }
    }

    /**
     * 开始验证码倒计时
     * 设置60秒倒计时，更新按钮状态和文本
     */
    const startCountDown = () => {
      cooldown.value = 60
      const timer = setInterval(() => {
        cooldown.value--
        if (cooldown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }

    /**
     * 发送验证码
     * 验证手机号并发送验证码请求
     */
    const sendVerificationCode = async () => {
      try {
        validateMobile()
        if (!isMobileValid.value) return

        const response = await sendSmsCode(formData.mobile)
        if (response.code === 200) {
          startCountDown()
        } else {
          ElMessage.error(response.message || '验证码发送失败')
        }
      } catch (error) {
        ElMessage.error('发送验证码失败，请稍后重试')
      }
    }

    /**
     * 检查密码是否包含数字
     * @returns {boolean} 是否包含数字
     */
    const hasNumber = () => {
      return /\d/.test(formData.password)
    }

    /**
     * 检查密码是否包含字母
     * @returns {boolean} 是否包含字母
     */
    const hasLetter = () => {
      return /[a-zA-Z]/.test(formData.password)
    }

    /**
     * 检查密码长度是否符合要求
     * @returns {boolean} 长度是否足够
     */
    const isLongEnough = () => {
      return formData.password.length >= 6
    }

    /**
     * 检查密码是否符合所有要求
     * @returns {boolean} 密码是否有效
     */
    const isPasswordValid = () => {
      return hasNumber() && hasLetter() && isLongEnough()
    }

    /**
     * 验证身份证号格式
     * @returns {boolean} 身份证号是否有效
     */
    const validateIdCard = () => {
      const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (!formData.idCard) {
        idCardError.value = '请输入身份证号码'
        return false
      } else if (!idCardRegex.test(formData.idCard)) {
        idCardError.value = '身份证号码格式不正确'
        return false
      } else {
        idCardError.value = ''
        return true
      }
    }

    /**
     * 选择用户角色
     * @param {string} role - 角色类型（'student' 或 'teacher'）
     */
    const selectRole = (role) => {
      formData.role = role
    }

    /**
     * 处理表单提交
     * 验证表单数据并发送注册请求
     */
    const handleSubmit = async () => {
      // 验证密码
      if (!isPasswordValid()) {
        ElMessage.error('密码必须包含字母和数字，且不少于6位')
        return
      }

      // 验证确认密码
      if (formData.password !== formData.confirmPassword) {
        ElMessage.error('两次输入的密码不一致')
        return
      }

      // 验证验证码
      if (!formData.verificationCode) {
        ElMessage.error('请输入验证码')
        return
      }

      // 验证真实姓名
      if (!formData.realName.trim()) {
        ElMessage.error('请输入真实姓名')
        return
      }

      // 验证身份证号
      if (!validateIdCard()) {
        return
      }

      try {
        // 校验验证码
        const checkResponse = await checkSmsCode(formData.mobile, formData.verificationCode)
        
        if (checkResponse.code !== 200) {
          ElMessage.error('验证码错误')
          return
        }

        // 提交注册
        loading.value = true
        
        // 准备提交的数据
        const registerData = {
          user: {
            userName: formData.userName,
            mobile: formData.mobile,
            password: formData.password,
            education: formData.education,
            role: formData.role,
            realName: formData.realName,
            idCard: formData.idCard
          },
          teacher: formData.role === 'teacher' ? {
            teachingAge: teacherData.teachingAge,
            teachingStyle: teacherData.teachingStyle,
            certification: teacherData.certification,
            introduction: teacherData.introduction
          } : null
        }
        
        const response = await register(registerData)
        
        if (response.code === 200) {
          ElMessage.success('注册成功')
          router.push('/login')
        } else {
          ElMessage.error(response.message || '注册失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    return {
      formData,
      teacherData,
      cooldown,
      loading,
      showPasswordTip,
      mobileError,
      isMobileValid,
      idCardError,
      showPassword,
      showConfirmPassword,
      sendVerificationCode,
      validateMobile,
      validateIdCard,
      handleSubmit,
      hasNumber,
      hasLetter,
      isLongEnough,
      isPasswordValid,
      selectRole
    }
  }
}
</script>

<style scoped>
/* 添加全局背景样式 */
.register-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  background: #fff;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  position: relative;
  overflow-y: auto;
}

/* 确保返回顶部组件在注册页面正常显示 */
:deep(.back-to-top) {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 9999;
}

.register-box {
  display: flex;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.05);
  width: 1200px;
  min-height: 700px;
  overflow: hidden;
}

.register-left {
  flex: 1.2;
  background: #e9ecef;
  padding: 40px;
  display: flex;
  flex-direction: column;
}

.register-right {
  flex: 1;
  padding: 60px 80px;
  background: white;
}

.register-header {
  text-align: center;
  margin-bottom: 24px;
}

.register-header h1 {
  color: #1f2937;
  font-size: 2.5rem;
  margin-bottom: 1rem;
}

.register-header p {
  color: #6b7280;
  font-size: 1.1rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.input-group {
  position: relative;
  display: flex;
  align-items: center;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.input-group:focus-within {
  border-color: #1890ff;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
}

.input-icon {
  padding: 0 1rem;
  color: #9ca3af;
}

input, select {
  width: 100%;
  padding: 0.75rem;
  background: transparent;
  border: none;
  font-size: 1rem;
  color: #1f2937;
  outline: none;
}

select {
  cursor: pointer;
}

.form-footer {
  text-align: center;
}

.submit-btn {
  width: 100%;
  padding: 1rem;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 1.5rem;
}

.submit-btn:hover:not(:disabled) {
  background: #096dd9;
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.login-link {
  color: #6b7280;
}

.login-link a {
  color: #1890ff;
  text-decoration: none;
  font-weight: 500;
  margin-left: 0.5rem;
}

.login-link a:hover {
  text-decoration: underline;
}

@media (max-width: 1024px) {
  .register-box {
    width: 800px;
  }
  
  .register-right {
    padding: 40px;
  }
}

@media (max-width: 768px) {
  .register-left {
    display: none;
  }
  
  .register-box {
    width: 100%;
    max-width: 500px;
  }
}

/* 验证码输入框组样式 */
.verification-group {
  display: flex;
  align-items: center;
}

.verification-group input {
  flex: 1;
}

.send-code-btn {
  padding: 0.5rem 1rem;
  margin-right: 0.5rem;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.send-code-btn:hover:not(:disabled) {
  background: #096dd9;
}

.send-code-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.password-tip {
  margin-top: 0.5rem;
  padding: 0.5rem;
  background: #f8f9fa;
  border-radius: 8px;
  font-size: 0.9rem;
  color: #6b7280;
}

.password-tip p {
  margin: 0 0 0.5rem 0;
  font-weight: 500;
}

.password-tip ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

.password-tip li {
  margin: 0.2rem 0;
  color: #9ca3af;
}

.password-tip li.valid {
  color: #10b981;
}

/* 输入框聚焦时的提示框样式 */
.input-group:focus-within + .password-tip {
  border: 1px solid #e5e7eb;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 替换角色选择器样式为更小巧的版本 */
.role-input-group {
  padding: 0;
  overflow: hidden;
}

.role-mini-selector {
  display: flex;
  width: 100%;
  height: 100%;
  align-items: stretch;
}

.role-mini-option {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0.75rem 0.5rem;
  cursor: pointer;
  transition: all 0.2s ease;
  background-color: transparent;
  gap: 6px;
}

.role-mini-option:hover {
  background-color: #f0f9ff;
}

.role-mini-option.active {
  background-color: #e6f7ff;
  color: #1890ff;
  font-weight: 500;
}

.role-mini-icon {
  font-size: 1.1rem;
}

.role-divider {
  width: 1px;
  background-color: #e5e7eb;
}

/* 在style中添加密码显示图标和身份证验证错误信息样式 */
.password-toggle {
  margin-right: 0.5rem;
  cursor: pointer;
  padding: 0.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #9ca3af;
  transition: color 0.2s ease;
}

.password-toggle:hover {
  color: #1890ff;
}

.eye-icon {
  font-size: 1.2rem;
  line-height: 1;
}

.error-message {
  color: #f56c6c;
  font-size: 0.85rem;
  margin-top: 0.3rem;
  display: block;
}

/* 添加教师字段相关样式 */
.teacher-fields {
  margin-top: 1.5rem;
  padding-top: 1rem;
  border-top: 1px dashed #e5e7eb;
}

.teacher-section-title {
  font-size: 1.1rem;
  color: #1f2937;
  margin-bottom: 1rem;
  font-weight: 500;
}

.textarea-group {
  height: auto;
  align-items: flex-start;
}

.textarea-group .input-icon {
  padding-top: 0.75rem;
}

textarea {
  width: 100%;
  padding: 0.75rem;
  background: transparent;
  border: none;
  font-size: 1rem;
  color: #1f2937;
  outline: none;
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

.brand {
  margin-bottom: 1rem;
}

.logo {
  font-size: 2.5rem;
  font-weight: bold;
  color: #343a40;
  margin-bottom: 1rem;
}

.brand h1 {
  font-size: 2rem;
  color: #1f2937;
  margin-bottom: 0.5rem;
}

.slogan {
  font-size: 1.2rem;
  color: #6b7280;
  margin-bottom: 2rem;
}

.features {
  margin: 2rem 0;
}

.feature-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.feature-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.feature-icon {
  font-size: 2rem;
  margin-right: 1rem;
  padding: 0.5rem;
  background: #f3f4f6;
  border-radius: 8px;
}

.feature-text h3 {
  font-size: 1.1rem;
  color: #1f2937;
  margin-bottom: 0.25rem;
}

.feature-text p {
  font-size: 0.9rem;
  color: #6b7280;
  line-height: 1.4;
}

.brand-image {
  width: 100%;
  max-width: 500px;
  height: 300px;
  margin-top: 1rem;
  margin-left: 10px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.brand-image:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}
</style> 